import pygame
import os
import sys
import cv2
import numpy as np

# 添加全局变量
video_playing = False
cap = None
clock = pygame.time.Clock()

def resource_path(relative_path):
    try:
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")
    return os.path.join(base_path, relative_path)

# 初始化Pygame
pygame.init()
font_path = resource_path("山海藏拙手书 W_mianfeiziti.com.ttf")
try:
    font = pygame.font.Font(font_path, 40)
except FileNotFoundError:
    font = pygame.font.SysFont("sans", 40)

TEXT_COL = (255, 255, 255)  # 白色
TEXT_COL1 = (0, 0, 205)  # 蓝色
TEXT_COL3 = (255, 0, 0)  # 红色

# 创建窗口，使用双缓冲技术优化视频播放
screen = pygame.display.set_mode((1079, 806), pygame.DOUBLEBUF)
pygame.display.set_caption("掐丝珐琅画")

# 导入图片素材
try:
    blackground1 = pygame.image.load(resource_path("主封面.jpg"))
    blackground2 = pygame.image.load(resource_path("手工桌面(1).png"))
    blackground3 = pygame.image.load(resource_path("背景三.png"))
    jiandao = pygame.image.load(resource_path("剪刀.png"))
    caisha = pygame.image.load(resource_path("彩砂.png"))
    huamiandiban = pygame.image.load(resource_path("画面底板1.png"))
    zhansijiao = pygame.image.load(resource_path("粘丝胶.png"))
    jinsi = pygame.image.load(resource_path("金丝.png"))
    chandao = pygame.image.load(resource_path("铲刀.png"))
    niezi = pygame.image.load(resource_path("镊子.png"))
    fgtp = pygame.image.load(resource_path("富贵太平.png"))
    ynm = pygame.image.load(resource_path("云南美.png"))
    dhzj = pygame.image.load(resource_path("说法图（细节）.jpg"))
except pygame.error as e:
    print(f"图片加载错误: {e}")
    pygame.quit()
    quit()

# 定义游戏变量
game_paused = False
menu_state = "main"  # 当前菜单状态
current_image = None  # 当前显示的图片
current_text = None  # 当前显示的文本
current_text_rect = None  # 当前文本的位置

# 按钮类
class Button:
    def __init__(self, x, y, image, scale):
        width = image.get_width()
        height = image.get_height()
        self.image = pygame.transform.scale(image, (int(width * scale), int(height * scale)))
        self.rect = self.image.get_rect()
        self.rect.topleft = (x, y)
        self.clicked = False

    def draw(self, surface):
        action = False
        pos = pygame.mouse.get_pos()  # 获取鼠标位置

        # 检查鼠标是否在按钮上
        if self.rect.collidepoint(pos):
            if pygame.mouse.get_pressed()[0] == 1 and not self.clicked:  # 检测左键点击
                self.clicked = True
                action = True

        if pygame.mouse.get_pressed()[0] == 0:  # 鼠标左键未按下
            self.clicked = False

        # 绘制按钮
        surface.blit(self.image, (self.rect.x, self.rect.y))
        return action

# 创建按钮Surface并绘制文本
def create_button_surface(width, height, text, font, text_color, bg_color):
    surface = pygame.Surface((width, height))
    surface.fill(bg_color)  # 填充背景颜色
    text_surface = font.render(text, True, text_color)  # 渲染文本
    text_rect = text_surface.get_rect(center=(width // 2, height // 2))  # 文本居中
    surface.blit(text_surface, text_rect)  # 将文本绘制到Surface上
    return surface

# 创建按钮实例
resume_button = Button(50, 200, create_button_surface(200, 50, "继续游戏", font, TEXT_COL, (0, 128, 0)), 1)
options_button = Button(50, 300, create_button_surface(200, 50, "制作工艺", font, TEXT_COL, (0, 128, 0)), 1)
quit_button = Button(50, 750, create_button_surface(200, 50, "退出游戏", font, TEXT_COL, (128, 0, 0)), 1)
master_button = Button(50, 500, create_button_surface(200, 50, "名家作品", font, TEXT_COL, (0, 128, 0)), 1)
jinsi_button = Button(50, 100, create_button_surface(200, 50, "金丝", font, TEXT_COL, (0, 128, 0)), 1)
chandao_button = Button(50, 180, create_button_surface(200, 50, "铲刀", font, TEXT_COL, (0, 128, 0)), 1)
caisha_button = Button(50, 260, create_button_surface(200, 50, "彩砂", font, TEXT_COL, (0, 128, 0)), 1)
huamiandiban_button = Button(50, 340, create_button_surface(200, 50, "画面底板", font, TEXT_COL, (0, 128, 0)), 1)
zhansijiao_button = Button(50, 420, create_button_surface(200, 50, "粘丝胶", font, TEXT_COL, (0, 128, 0)), 1)
jiandao_button = Button(50, 500, create_button_surface(200, 50, "剪刀", font, TEXT_COL, (0, 128, 0)), 1)
niezi_button = Button(50, 580, create_button_surface(200, 50, "镊子", font, TEXT_COL, (0, 128, 0)), 1)
back_button = Button(50, 660, create_button_surface(200, 50, "返回", font, TEXT_COL, (128, 0, 0)), 1)  # 返回按钮
fgtp_button = Button(50, 200, create_button_surface(200, 50, "云南美", font, TEXT_COL, (0, 128, 0)), 1)
ynm_button = Button(50, 300, create_button_surface(200, 50, "富贵太平", font, TEXT_COL, (0, 128, 0)), 1)
dhzj_button = Button(50, 400, create_button_surface(200, 50, "风景画", font, TEXT_COL, (0, 128, 0)), 1)
history_button = Button(50, 400, create_button_surface(200, 50, "制作教程", font, TEXT_COL, (0, 128, 0)), 1)

# 文本提示
def draw_text(text, font, text_color, x, y):
    img = font.render(text, True, text_color)
    screen.blit(img, (x, y))

# 绘制名家子界面
def draw_master_sub_menu():
    global menu_state, current_image, current_text
    screen.blit(blackground3, (0, 0))  # 绘制背景

    # 绘制返回按钮
    if back_button.draw(screen):
        print("名家子界面返回按钮被点击")
        menu_state = "main"  # 返回主菜单
        current_image = None  # 清除当前显示的图片
        current_text = None  # 清除当前显示的文本

    # 绘制其他按钮
    if fgtp_button.draw(screen):
        print("富贵太平按钮被点击")
        current_image = fgtp
    if ynm_button.draw(screen):
        print("云南美按钮被点击")
        current_image = ynm
    if dhzj_button.draw(screen):
        print("敦煌藻井按钮被点击")
        current_image = dhzj

    # 绘制当前图片
    if current_image is not None:
        screen.blit(current_image, (370, 50))  # 绘制图片到右侧

# 绘制操作子界面
def draw_options_sub_menu():
    global current_image, current_text, current_text_rect, menu_state
    screen.blit(blackground2, (0, 0))  # 绘制背景，覆盖整个屏幕

    # 绘制当前图片
    if current_image is not None:
        screen.blit(current_image, (370, 50))  # 绘制图片到右侧

    # 绘制按钮
    if jinsi_button.draw(screen):
        print("金丝按钮被点击")
        current_image = jinsi
    if chandao_button.draw(screen):
        print("铲刀按钮被点击")
        current_image = chandao
    if caisha_button.draw(screen):
        print("彩砂按钮被点击")
        current_image = caisha
    if huamiandiban_button.draw(screen):
        print("画面底板按钮被点击")
        current_image = huamiandiban
    if zhansijiao_button.draw(screen):
        print("粘丝胶按钮被点击")
        current_image = zhansijiao
    if jiandao_button.draw(screen):
        print("剪刀按钮被点击")
        current_image = jiandao
    if niezi_button.draw(screen):
        print("镊子按钮被点击")
        current_image = niezi
    if back_button.draw(screen):
        print("制作工艺菜单返回按钮被点击")
        menu_state = "main"  # 返回主菜单
        # 清除当前显示的图片和文本
        current_image = None
        current_text = None
        current_text_rect = None

# 绘制主菜单
def draw_main_menu():
    global game_paused, menu_state, run
    screen.blit(blackground1, (0, 0))  # 绘制背景

    if resume_button.draw(screen):
        game_paused = False  # 继续游戏
    if options_button.draw(screen):
        menu_state = "options"  # 进入选项子菜单
    if history_button.draw(screen):
        menu_state = "history"
        print("历史按钮被点击")
    if master_button.draw(screen):
        menu_state = "master"  # 进入名家子菜单
    if quit_button.draw(screen):
        run = False  # 退出游戏

# 绘制历史沿革子界面
def draw_history_sub_menu():
    global menu_state, video_playing, cap

    screen.blit(blackground3, (0, 0))  # 绘制背景

    # 初始化视频播放
    if not video_playing:
        video_path = resource_path("掐丝珐琅画教程.mp4")
        if not os.path.exists(video_path):
            print("视频文件不存在")
            return
        cap = cv2.VideoCapture(video_path)
        if not cap.isOpened():
            print("无法打开视频文件")
            return
        video_playing = True

    # 处理视频帧
    ret, frame = cap.read()
    if ret:
        try:
            # 颜色转换和尺寸调整
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            frame = cv2.resize(frame, (1079, 806))
            
            # 镜像修正
            frame = cv2.flip(frame, 1)  # 水平翻转解决镜像
            frame = cv2.flip(frame, 1)  # 再次水平翻转恢复原状
            
            # 使用硬件加速
            frame_surface = pygame.surfarray.make_surface(frame.swapaxes(0, 1))
            screen.blit(frame_surface, (0, 0))
        except Exception as e:
            print(f"视频帧处理错误: {e}")
    else:
        # 视频结束后循环播放
        cap.set(cv2.CAP_PROP_POS_FRAMES, 0)

    # 绘制返回按钮
    if back_button.draw(screen):
        menu_state = "main"
        if cap is not None:
            cap.release()
            video_playing = False

# 游戏主循环
run = True
while run:
    # 控制整体帧率
    clock.tick(30)

    # 清空屏幕
    screen.fill((0, 0, 0))  # 用黑色填充屏幕，清除之前的内容

    # 根据菜单状态绘制内容
    if game_paused:
        if menu_state == "main":
            draw_main_menu()  # 绘制主菜单
        elif menu_state == "options":
            draw_options_sub_menu()  # 绘制选项子菜单
        elif menu_state == "master":
            draw_master_sub_menu()  # 绘制名家子界面
        elif menu_state == "history":  # 新增历史沿革子菜单
            draw_history_sub_menu()
            pygame.display.update()  # 强制更新画面
    else:
        # 游戏运行时的界面
        draw_text("按空格键暂停进入菜单", font, TEXT_COL1, 343, 390)

    # 绘制当前图片和文本
    if current_image is not None and menu_state == "history":
        screen.blit(current_image, (300, 100))  # 绘制图片到右侧
    if current_text is not None:
        screen.blit(current_text, current_text_rect)  # 绘制文本

    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False  # 退出游戏
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                game_paused = not game_paused  # 切换暂停状态
            elif event.key == pygame.K_ESCAPE:
                if game_paused:
                    if menu_state == "main":
                        run = False  # 退出游戏
                    else:
                        menu_state = "main"  # 返回主菜单

    # 正常更新流程
    pygame.display.flip()

# 退出时释放资源
if cap is not None and cap.isOpened():
    cap.release()
cv2.destroyAllWindows()

# 退出Pygame
pygame.quit()


